package com.book.oauth.config;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.book.common.util.DatetimeUtil;
import com.google.common.collect.Maps;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.Date;
import java.util.Map;

/**
 * Description： 自定义生成token规则
 * @Author： leo.xiong
 * @CreateDate： 2019/10/11 15:40
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
public class CustomTokenEnhancer implements TokenEnhancer {

    private String secretKeySpec;

    public void setSecretKeySpec(String secretKeySpec) {
        this.secretKeySpec = secretKeySpec;
    }

    /**
     * 重新生成token，token包含 加密的KEY+时间戳+UUID
     *
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInfo = Maps.newHashMap();
        additionalInfo.put("oauthTime", DatetimeUtil.formatDate(new Date(), DatetimeUtil.YYYY_MM_DD_HH_MM_SS_L_C));
        additionalInfo.putAll(authentication.getOAuth2Request().getRequestParameters());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        ((DefaultOAuth2AccessToken) accessToken).setValue(secretKeySpec + StringPool.DASH + System.currentTimeMillis() + StringPool.DASH + accessToken.getValue());
        return accessToken;
    }

}
